<?php session_start() ?>
<!DOCTYPE html>
<html>
<head>
	<title>welcome</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
	<link rel="stylesheet" href="stylesheet.css">

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>

<body> 

<!-- Sell property form. It has two parts. 
	First part uploads multiple images to server directory and creates array of file names.
	Second part (after submit button) checks array and if any names adds them to DB with all other info.
	It has to have restrictions on file sizes, types and quantities.
	Also in real life this requires captcha, session control, passwords so on
	Also all file names have to be unique to prevent conflicts in directory/ DB
	Also if user adds images and no other info those images have to be deleted later on-->

 <?php

require 'header.php';
// create_db should be somewere on landing page and executed only once
require_once 'create_db.php'; 
require_once 'connect.php';

$city = $suburb = $street_name = $street_num = $bedrooms_num = $price = $description = "";
$city_err = $suburb_err = $street_name_err = $street_num_err = "";
$image_err = $bedrooms_num_err = $price_err = $description_err = $status = $statusMsg  = "";

//this array is to contain images names to add to DB in second part 
//it has to be session array because POST unsets all variables 
//so after using it it has to be unset:

if (!isset($_SESSION['imagesUrlsToAdd'])){
          $_SESSION['imagesUrlsToAdd'] = array();
        }
$sessionArray = $_SESSION['imagesUrlsToAdd'];

/* 
 * Custom function to compress image size and 
 * upload to the server
 */ 
function compressImage($source, $destination, $quality) { 

    //getimagesize returns array with image info
    $imgInfo = getimagesize($source); 
    $mime = $imgInfo['mime'];
     
    // Create a new image from file 
    switch($mime){ 
        case 'image/jpeg': 
            $image = imagecreatefromjpeg($source); 
            break; 
        case 'image/png': 
            $image = imagecreatefrompng($source); 
            break; 
        case 'image/gif': 
            $image = imagecreatefromgif($source); 
            break; 
        default: 
            $image = imagecreatefromjpeg($source); 
    } 
     
    // Save image 
    imagejpeg($image, $destination, $quality); 
    // echo($destination);     /////////////displaying result 4 checking


    // Return compressed image path
    return $destination; 
}

//This function takes a value from form input extracts only numbers first 
//and then checks if they are in proper range. It uses php's regular expressions

function sanitize_string($string, $min='', $max='')
{
  $string = preg_replace("/[^0-9]/", "", $string);
  $len = strlen($string);
  if((($min != '') && ($len < $min)) || (($max != '') && ($len > $max))){
  	return FALSE;
  }
  else{
  		return $string;
  }
}

/////////////////////////////////////////////////////////////////////////
 			// If file upload form is submitted 
if(isset ($_POST["upload"])){

//File upload path
//This directory if on unix like servers should have '777' permissions
//to be able to upload to. Also it has to be created at the root of the project folder

$targetDir = "photos/";
$status = 'error'; 

	if(!empty($_FILES["imageToUpload"]["name"])){

		// getting file info from input array $_FILES["imageToUpload"]
		// print_r($_FILES["imageToUpload"]); //////////////4 error checking

        $fileName = basename($_FILES["imageToUpload"]["name"]); 
        // Image temp source
        $imageTemp = $_FILES["imageToUpload"]["tmp_name"]; 
        $imageError = $_FILES["imageToUpload"]["error"];
        //one more way to get file type in php
        $imageType = $_FILES["imageToUpload"]["type"];
		$imageSize = $_FILES["imageToUpload"]["size"];

        //	This takes extention of file and checks if it's in array
        $fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); 
        $allowTypes = array('jpg','png','jpeg','gif'); 

		//this makes unique file name 
		//so  no files going to be overwritten
        $fileNameUnique = uniqid('',true).".".$fileType;
		$imageToUploadPath = $targetDir.$fileNameUnique; 
		// echo "$imageToUploadPath <br>";/////////////displaying result 4 checking

        if(in_array($fileType, $allowTypes)){ 
        	if (!($imageError)) {
        		//minimum size restriction can be set as well
        		if ($imageSize < 10000000){

		            // Compress size and upload image 
		            $compressedImagePath = compressImage($imageTemp, $imageToUploadPath, 75);
		            // $compressedImagePath = basename($compressedImagePath);
		            // echo "$compressedImagePath<br>"; //////////////displaying result 4 checking

					// $imageToUploadPath	= $targetDir.$fileNameUnique;
		            // move_uploaded_file($compressedImagePath, $imageToUploadPath);

		            if($compressedImagePath){
		            	$_SESSION['imagesUrlsToAdd'][] = "$compressedImagePath"; 
		            	$status = "image accepted";	

			        } else
			        	{ $statusMsg = 'Some error(s) occured with image compression.'; } 
		       	        	   
        		} else 
        			{ $statusMsg = 'This image size is too big. Please choose smaller one.';}
	        	 
        	} else 
        		{ $statusMsg = "some error with file upload"; }
        		
		} else 
			{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; }

	} else 
		{ $statusMsg = 'Please select an image file to upload.'; } 
}

////////////////////////////////////////////////////////////////////////////////////
			//SECOND PART

if(isset($_POST["submit"])){

	// checking if everything is filled in
	// also all fields which require some numbers, 
	// better make integers in DB so it easier for search later on

	// checking if at least one image path is in array
	if(empty($sessionArray)){
		
		$image_err = "Please upload property image(s) |";	
	}
	

	if(empty(trim($_POST["city"]))){

		$city_err = "Please provide city name |";
	}
	else{
		$city = trim($_POST["city"]);
	}

	if(empty(trim($_POST["suburb"]))){

		$suburb_err = "Please provide name of suburb |";
	}
	else{
		$suburb = trim($_POST["suburb"]);
	}

	if(empty(trim($_POST["street_name"]))){

		$street_name_err = "Please provide street name |";
	}
	else{
		$street_name = trim($_POST["street_name"]);
	}

	if(empty(trim($_POST["street_num"]))){
		$street_num_err = "Please provide street number |";
	}
	else{
	
		$street_num = trim($_POST["street_num"]);
		$street_num = sanitize_string($street_num, 0,100000) ? $street_num : FALSE;
		// $street_num = is_numeric($street_num ) ? $street_num : FALSE;
		if (!$street_num) {
			echo("no street number "); 
		}else {
			// echo($street_num."<br>");//////////////echoing result 4 checking
			}	
	}

	if(empty(trim($_POST["bedrooms_num"]))){
		$bedrooms_num_err = "Please provide number of bedrooms |";
	}
	else{
		// To validate form data (string) as an integer ctype_digit() can be used.
		// It returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
		//Reference: http://php.net/manual/en/function.ctype-digit.php

		if(ctype_digit($_POST["bedrooms_num"])){

//		INTVAL Returns the int value of var, using the specified base for the conversion (the default is base 10). 
			$bedrooms_num = intval(trim($_POST["bedrooms_num"]));

			// echo($bedrooms_num);/////////////////////echoing result 4 error checking

		}else{
			$bedrooms_num_err = "Please use numbers only |";
		}		
	}

	if (empty(trim($_POST["price"]))) {

		$price_err = "Please provide asking price |";
	} 
	else {

		if(ctype_digit($_POST["price"])){

			$price = intval(trim($_POST["price"]));	

			// echo "<br>$price";	////////////////////	echoing result 4 error checking
		}
		else{
			$price_err = "Please use numbers only |";
		}		
	}

	if (empty(trim($_POST["description"]))) {
		$description_err = "Please provide description |";
	} 
	else {
		$description = trim($_POST["description"]);
	}

// 	if no errors, adding everything to DB:

	if(empty($image_err) && empty($city_err) && empty($suburb_err) && empty($street_name_err) && empty($street_num_err) && empty($bedrooms_num_err) && empty($price_err) && empty($description_err)){
						 	
			//prepared  statements. second statement takes last id for using in other tables
		$sql = "INSERT INTO properties( user_id, bedrooms, price, description) VALUES(?,?,?,?)";

		$stmt = $conn->prepare($sql);
		$stmt->bind_param('iiis', $param_id, $bedrooms_num, $price, $description);

		//getting user id of logged in user. It has been set in login.php or register.php
		$param_id = $_SESSION['user_id'];

			if($stmt->execute()){
				echo "Your property info has been successfully added to DB!! <br>";
				//this takes last created id from $sql
				 $property_id = $conn->insert_id;
				 // echo('<br>' .$property_id. '<br>'); /////////////////echoing result 4 error checking

				} else { echo("there is some error with DB query in first query<br>"); }

//						inserting address

		$sql =	"INSERT INTO addresses(property_id, city, suburb, street_name, street_number) VALUES(?, ?, ?, ?, ?)";
		$stmt = $conn->prepare($sql);
		$stmt->bind_param('isssi', $property_id, $city, $suburb, $street_name, $street_num);
		if($stmt->execute()){
				echo "Your address has been successfully added to DB!! <br>";
			}
		 	else {
		 		echo "error in second query <br>";
		 	}

//						inserting all photo urls

		 $sql =	"INSERT INTO photos(property_id, photo_url) VALUES(?, ?)";
		 $stmt = $conn->prepare($sql);
		 $stmt->bind_param('is', $property_id, $param_photo_url);
		
		 foreach ($sessionArray as $urlToAdd) {
		 	$property_id = $property_id;
		 	$param_photo_url = $urlToAdd;

			if($stmt->execute()){
				echo "Your image(s) has been successfully added to DB!! <br>";
			}
		 	else {
		 		echo "error in second query <br>";
		 	}
		 }
		 //this will remove $sessionArray and $_SESSION['imagesUrlsToAdd'] ...
		 //no need for them any more 
		 //reference https://stackoverflow.com/questions/10261925/best-way-to-clear-a-php-arrays-values

		 unset($_SESSION['imagesUrlsToAdd']);
		 unset($sessionArray);
		 // print_r($_SESSION['imagesUrlsToAdd']);  ////////////////echoing result 4 error checking


		 $stmt->close();

					
		} else { echo("there is some data missing or not in suitable format<br>"); }


	}

	$conn->close();
?>
<div id="sell-from-wrapper" class="">
	<div id="sell-wrapper" class="sell-wrapper sell-form-section sell-form-bk">
		<h2 id="sell-property-text">Sell Property</h2>

		<!-- First part... property images-->
		<form method="post"  class="upload-img-section <?php echo (!empty($image_err))?'has error':''?>" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" enctype="multipart/form-data">
			<div class="input-group">
				<input type="file" class="btn-max btn-size" name="imageToUpload">
				<div id="upl-btn-wrp" class="input-group-append">
					<button id="upl-btn" type="submit" class="btn-max" value="Upload" name="upload">Upload image(s)</button>	
				</div>
				<span class="help-block"><?php echo $image_err," ", $status," ", $statusMsg; ?></span>
			</div>		
		</form>
		<br>

		<!-- Second part -->
		<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
			<div class="input-group">
				<div class="fields-wrapper form-group input-group-prepend">
					<input class="fields" type="text" name="city" class="form-control <?php echo $city; ?>" placeholder="City">
					
				</div>
				<div class="fields-wrapper form-group">
					<input class="fields" type="text" name="suburb" class="form-control <?php echo $suburb; ?>" placeholder="Suburb">
				</div>
				<span class="help-block"><?php echo $city_err; ?> </span><span class="help-block"><?php echo $suburb_err; ?> </span>
			</div>
			<br>
			<div class="input-group">
				<div class="fields-wrapper form-group input-group-prepend">
					<input class="fields" type="text" name="street_name" class="form-control <?php echo $street_name; ?>" placeholder="Street name">
				</div>
				<div class="fields-wrapper form-group">
					<input class="fields" type="text" name="street_num" class="form-control <?php echo $street_num; ?>" placeholder="Street number">
						
				</div>
				<span class="help-block"><?php echo $street_name_err; ?> </span> <span class="help-block"><?php echo $street_num_err; ?></span>
			</div>
			<br>
			<div class="input-group">
				<div class="fields-wrapper input-group-prepend form-group <?php echo (!empty($bedrooms_num_err))?'has error':''?>">
					<input class="fields" type="text" name="bedrooms_num" class="form-control <?php echo $bedrooms_num; ?>" placeholder="Number of bedrooms">
				</div>
				<div class="fields-wrapper form-group <?php echo (!empty($price_err))?'has error':''?>">
					<input class="fields" type="text" name="price" class="form-control <?php echo $price; ?>" placeholder="Price asking">	
				</div>
					<span class="help-block"><?php echo $bedrooms_num_err; ?> </span><span class="help-block"><?php echo $price_err; ?></span>	

			</div>
			<br>
			<div class="form-group p-desc-wrapper<?php echo (!empty($description_err))?'has error':''?>">
				<textarea class="form-control p-desc-field <?php echo $description; ?>" rows="5" name="description" placeholder="Property description"></textarea>
			</div>
			<span class="help-block"><?php echo $description_err; ?></span>
			<div class="form-group">
				<div class="input-group btn-group">
					<input id="reset-btn" type="reset" class="btn-max btn-size" value="Reset">
					<input type="submit" name="submit" class="btn-max btn-size" value="Submit">
				</div>	
			</div>
		</form> 	
	</div>
</div>

</body>
</html>